package com.swotplus.framework.config;

import com.swotplus.framework.util.DictionaryUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;

@Component
public class MyContextListener implements ApplicationListener<ContextRefreshedEvent> {

    /**
     * 所有bean加载完成之后要做的逻辑
     * @param event
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext ac = event.getApplicationContext();
        Environment environment=(Environment)ac.getBean("environment");
        // 将 ApplicationContext 转化为 WebApplicationContext
        WebApplicationContext webApplicationContext =(WebApplicationContext)ac;
        ServletContext servletContext = webApplicationContext.getServletContext();
        String domain = environment.getProperty("server.domain");
        String port = environment.getProperty("server.port");
        String contextPath = domain;
        servletContext.setAttribute("basePath", contextPath);
        servletContext.setAttribute("dict", DictionaryUtil.init());
    }
}
